package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.config.BaseContext;
import com.example.entity.ShoppingCart;
import com.example.mapper.ShoppingCartMapper;
import com.example.service.ShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author lw
 * @since 2023-01-31
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public R<ShoppingCart> addCar(ShoppingCart shoppingCart) {
        shoppingCart.setUserId(BaseContext.getThreadLocal());
        //查询当前菜品或者套餐是否在购物车中
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getThreadLocal());

        if (shoppingCart.getDishId() != null){
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else {
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart one = this.getOne(queryWrapper);
        if (shoppingCart.getName()==null){
            one.setNumber(one.getNumber()-1);
            this.updateById(one);
        }else {
            if (one != null){
                one.setNumber(one.getNumber()+1);
                this.updateById(one);
            }else{
                shoppingCart.setNumber(1);
                shoppingCart.setCreateTime(LocalDateTime.now());
                this.save(shoppingCart);
                one = shoppingCart;
            }
        }
        return R.success(one);
    }

    @Override
    public R<List<ShoppingCart>> getList() {
        LambdaQueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartQueryWrapper.eq(ShoppingCart::getUserId,BaseContext.getThreadLocal());
        shoppingCartQueryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = this.list(shoppingCartQueryWrapper);
        return R.success(list);
    }

    @Override
    public R<String> clean() {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getThreadLocal());
        this.remove(queryWrapper);
        return R.success("清空购物车成功");
    }


}
